<template>
  <el-dialog
    v-el-drag-dialog
    title="新增安检任务单"
    :visible.sync="visible"
    width="700px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="90px">
      <el-form-item label-width="0" prop="csmText">
        <el-input v-model.trim="temp.csmText" placeholder="请输入">
          <el-select slot="prepend" v-model="csmVal" style="width: 100px;" placeholder="请选择">
            <el-option label="电话" value="csmRgPhone" />
            <el-option label="客户编号" value="csmCode" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label-width="0">
        <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
      <div class="form-icon">
        <div><i class="el-icon-price-tag" />&nbsp;&nbsp;编号&nbsp;:&nbsp;<span>{{ data.csmCode }}</span></div>
        <div><i class="el-icon-user" />&nbsp;&nbsp;名称&nbsp;:&nbsp;<span>{{ data.csmName }}</span></div>
        <p><i class="el-icon-bank-card" />&nbsp;&nbsp;身份证&nbsp;:&nbsp;<span>{{ data.sfzh }}</span></p>
      </div>
      <el-form-item label="联系人:" prop="contact">
        <el-select v-model="temp.contact" style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="(i, ind) in phoneList"
            :key="ind"
            :label="i.contact"
            :value="i.contact"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话:" prop="csmPhone">
        <el-select v-model="temp.csmPhone" placeholder="请选择">
          <el-option
            v-for="(i, ind) in phoneList"
            :key="ind"
            :label="i.csmPhone"
            :value="i.csmPhone"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="安检地址:" prop="csmAddressId" style="width: 100%;">
        <el-select v-model="temp.csmAddressId" placeholder="请选择">
          <el-option
            v-for="(i, ind) in addressList"
            :key="ind"
            :label="i.csmAddress"
            :value="i.csmAddressId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定司机:" prop="bindDriverName">
        <el-input v-model.trim="temp.bindDriverName" placeholder="请输入" disabled />
      </el-form-item>
      <el-form-item label="值班人:" prop="dutyName">
        <el-input v-model.trim="temp.dutyName" placeholder="请输入" disabled />
      </el-form-item>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="temp.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="处理人:" prop="newOwnerId">
        <el-select v-model="temp.newOwnerId" style="width: 100%;" placeholder="请选择" @change="chooseOwner">
          <el-option
            v-for="(i, ind) in ownersList"
            :key="ind"
            :label="i.userName"
            :value="i.userId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
    <confirmClasses ref="confirmClasses" :parent-fun="reset" />
  </el-dialog>
</template>

<script>
  import { organizationQueryList, csDeliverUserList, gasCheckTodoSave, gasCheckTodoMessage, orderDutyCheck } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { isWildPhone } from '@/utils'
  import confirmClasses from '@/views/components/ConfirmClasses'

  export default {
    name: 'add',
    components: {
      confirmClasses
    },
    data() {
      return {
        visible: false,
        csmVal: 'csmRgPhone',
        treeData: [],
        ownersList: [],
        params: {},
        data: {},
        phoneList: [],
        addressList: [],
        temp: {
          contact: '',
          csmText: '',
          csmPhone: '',
          csmAddressId: '',
          orgSNNo: '', // 责任机构orgSNNo
          newOwnerId: ''
        },
        rules: {
          contact: [{ required: true, message: '请选择联系人', trigger: 'change' }],
          csmPhone: [{ required: true, message: '请选择联系电话', trigger: 'change' }],
          csmAddressId: [{ required: true, message: '请选择安检地址', trigger: 'change' }],
          orgSNNo: [{ required: true, message: '请选择责任机构', trigger: 'change' }],
          newOwnerId: [{ required: true, message: '请选择处理人', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ])
    },
    async created() {
      await this.getTreeData()
    },
    methods: {
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          this.add()
        })
      },
      async add() {
        // 处理入参
        this.params.contact = this.temp.contact
        this.params.csmPhone = this.temp.csmPhone
        this.params.orgSNNo = this.temp.orgSNNo
        this.addressList.map(item => {
          if (item.csmAddressId === this.temp.csmAddressId) {
            this.params.csmAddress = item.csmAddress
            this.params.csmAddressId = item.csmAddressId
          }
        })
        this.ownersList.map(item => {
          if (item.userId === this.temp.newOwnerId) {
            this.params.checkUser = item.userName
            this.params.checkUserId = item.userId
          }
        })
        console.log('this.params', this.params)
        const res = await gasCheckTodoSave(this.params)
        console.log('...res', res)
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
        // 更新列表
        this.$emit('upDataTable')
      },
      // 查询
      async onSearch() {
        if (!this.temp.csmText) {
          this.$message.error('查询条件不能为空')
          return
        }
        if (this.csmVal === 'csmRgPhone') {
          if (!isWildPhone(this.temp.csmText)) {
            this.$message.error('请输入正确的电话号码!')
            return
          }
        }
        const query = {
          csmStatus: 9 // 查询状态不是已注销的客户
        }
        query[this.csmVal] = this.temp.csmText
        // 1.发送查询接口
        const res = await gasCheckTodoMessage(query)
        // 2.整理增加接口入参
        if (res && res.data) {
          this.data = res.data
          this.params.csmCode = res.data.csmCode
          this.params.csmName = res.data.csmName
          this.params.csmId = res.data.csmId
          this.params.csmType = res.data.csmType
          // 处理电话和地址
          this.temp.contact = res.data.contact
          this.temp.csmPhone = res.data.csmRgPhone
          this.temp.csmAddress = res.data.csmRgAddress
          this.temp.bindDriverName = res.data.bindDriverName
          this.temp.dutyName = res.data.dutyName
          res.data.addressItems.forEach((item) => {
            if (item.csmAddress === this.temp.csmAddress) {
              this.$set(this.temp, 'csmAddressId', item.csmAddressId)
              // this.temp.csmAddressId = item.csmAddressId
            }
          })
          this.phoneList = res.data.phoneItems.filter(item => item.cpStatus === 2)
          if (this.phoneList.length > 0) {
            this.$set(this.temp, 'contact', res.data.contact)
            this.$set(this.temp, 'csmPhone', res.data.csmRgPhone)
          }
          if (res.data.addressItems && res.data.addressItems.length > 0) {
            this.addressList = res.data.addressItems
            this.$set(this.temp, 'csmAddress', res.data.addressItems[0].csmAddressId)
          }
        } else {
          this.$message({
            message: '暂无信息',
            type: 'warning'
          })
        }
      },
      reset() {
        this.csmVal = 'csmRgPhone'
        this.data = {}
        this.ownersList = []
        this.temp = {
          contact: '',
          csmText: '',
          csmPhone: '',
          csmAddress: '',
          orgSNNo: '',
          newOwnerId: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
        this.visible = false
      },
      // 选择责任机构
      selectTreeChange(value) {
        this.temp.orgSNNo = value.orgSNNo
        this.params.orgId = value.orgId
        this.params.orgName = value.orgName
        this.temp.newOwnerId = ''
        this.getOwnersList(value.orgId)
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const res = await csDeliverUserList({ deliveryOrgId: orgId })
        this.ownersList = res.data
        console.log('res.data', res.data)
      },
      async chooseOwner(val) {
        if (val) {
          const res = await orderDutyCheck({ ownerId: val })
          if (res.data === 1) {
            const info = this.ownersList.find(item => item.userId === val)
            this.$refs.confirmClasses.open(info)
          }
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const res = await organizationQueryList({})
        const data = res.data.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .form-icon {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 20px;
    font-size: 15px;
    font-weight: 700;
    color: #606266;
    p {
      width: 50%;
    }
    span {
      font-size: 14px;
      color: #999;
    }
  }
}
</style>
